<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Sku as SkuService;
use app\common\service\SkuStockMap as SkuStockMapService;
use app\common\service\Order as OrderService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderDelivery as OrderDeliveryService;
use think\Console;
use mes\Mes;

/**
 * 尾部进度
 * @author King
 *
 */
class Tail extends Admin
{

	public function initialize() {
		parent::initialize();
	}

	public function index()
	{
		$factoryKV = getFactoryKV(false);
		$factoryOutgoKV = getFactoryOutgoKV(null);
		$systemUserKV = getSystemUserKV(null);
		$groupKV = getGroupKV(0);
        $export     = $this->request->param('export/d', 0);
		if ($this->request->isAjax() || $export>0) {
			$where      = $data = [];
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$factorId      = $this->request->param('factory_id/d', 0);
			$orderStatus    = $this->request->param('order_status/s');
			$clientOrdernum    = $this->request->param('client_ordernum/s');
			$sku    = $this->request->param('sku/s');
            $breakType    = $this->request->param('break_type/s','');
			$createDateRange    = $this->request->param('create_date_range/s');
			$overDateRange    = $this->request->param('over_date_range/s');
            $tail_over_time    = $this->request->param('tail_over_time/s');
            $search_delivery_status    = $this->request->param('delivery_status');
			$caichuangOverDateRange    = $this->request->param('caichuang_over_date_range/s');

			$where[] = ['status', 'in', [0,1,2]];
			$where[] = ['chejian_status', '=', 1];
            //订单加一级
            order_level($where,'');
			if ($factorId) {
				$where[] = ['factory_id', '=', $factorId];
			}

			if ($orderStatus != '') {
				switch ($orderStatus){
					case 1:
						$where[] = ['caigou_status', '=', 0];
						break;
					case 2:
						$where[] = ['caigou_status', '=', 1];
						$where[] = ['caichuang_status', '=', 0];
						break;
					case 3:
						$where[] = ['caichuang_status', '=', 1];
						$where[] = ['chejian_status', '=', 0];
						break;
					case 4:
						$where[] = ['chejian_status', '=', 1];
						$where[] = ['tail_status', '=', 0];
						break;
					case 5:
						$where[] = ['tail_status', '=', 1];
						$where[] = ['real_shipment_status', '=', 0];
						break;
					case 6:
						$where[] = ['real_shipment_status', '=', 1];
						$where[] = ['status', '=', 1];
						break;
					case 7:
						$where[] = ['status', '=', 2];
						break;
				}
			}
			if ($clientOrdernum != '') {
				$where[] = ['client_ordernum', '=', $clientOrdernum];
			}
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['ext_id', 'like', "%" . $ext_id . "%"];
                    break;
            }
			if ($sku != '') {
				$where[] = ['sku', 'like', "%".$sku."%"];
			}
			if ($createDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
				$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
			}
			if ($overDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $overDateRange));
				$where[] = ['over_time', 'between', [$startTime, $endTime+86399]];
			}
            if ($tail_over_time != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $tail_over_time));
                $where[] = ['tail_over_time', 'between', [$startTime, $endTime+86399]];
            }
			if ($caichuangOverDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverDateRange));
				$where[] = ['caichuang_over_time', 'between', [$startTime, $endTime+86399]];
			}
            if ($breakType != '') {
                $where[] = ['break_code_status', '=',$breakType];
                if($breakType !=1){
                    $where[] = ['tail_status', '<>', 1];
                }
            }
            $sqlwhere='';$joinType='left';
            if ($search_delivery_status != '') {
                //delivery_status 1=>'未全部入仓', 2=>'已全部入仓', 3=>'含已收货', 4=>'含已退货', 5=>'含待发货'
                $delivery_where=[
                    1=>'and chird_delivery_status<> "8"',
                    2=>'and chird_delivery_status = "8"',
                    3=>'and chird_delivery_status like "%5%"',
                    4=>'and chird_delivery_status like "%7%"',
                    5=>'and chird_delivery_status like "%3%"'
                ];
                $sqlwhere=$delivery_where[$search_delivery_status];
                $joinType='inner';
            }
            $usedStockData = db('order_delivery')
                ->field('order_id,group_concat(distinct delivery_status) as chird_delivery_status,group_concat(update_time) as chird_update_time')
                ->group('order_id')
                ->buildSql();
            if ($export) {
                set_time_limit(0);
                ini_set('memory_limit', '1024M');
                $page = 1;
                $limit = 99999;
                $data['count'] = db('order')
                    ->join([$usedStockData=> 'delivery'], 'o.id = delivery.order_id '.$sqlwhere,$joinType)
                    ->where($where)->count('id');
                if($data['count']>20000){//
                    echo "<script language='JavaScript'>alert('当前导出数据过大已超过2万条，请筛选后再选择导出');window.close()</script>";die;
                }
            }

			$order = "FIELD(status,2,99) ASC,tail_over_time asc,tail_status ASC,shipment_time ASC,create_time ASC";
			$data['data'] = db('order o')
                ->join([$usedStockData=> 'delivery'], 'o.id = delivery.order_id '.$sqlwhere,$joinType)
                ->where($where)->page($page)->limit($limit)->orderRaw($order)->select();

			// 获取有发货单的订单
			$orderDeliveryList = db('order_delivery')->where('order_id', 'in', array_column($data['data'], 'id'))->column('order_id');

			$skuService = new SkuService();
			$orderSizeService = new OrderSizeService();
			$orderMaterialService = new OrderMaterialService();
			foreach ($data['data'] as $k => $v) {
				$osList = $orderSizeService->getListByOrderId($v['id'], 'mid,order_count,daohuo_count,shicai_count,jiaohuo_tail_count,delivery_count,jiaohuo_count,size_name,tail_stock_in_out,tail_defective');
				$otherStockList=db('sku_stock')->where(['sku' => $v['sku']])->where('client_ordernum','not in',[$v['client_ordernum']])
                    ->field('dress_line_code,size_name,sum(available_count) as available_count,sum(defective_count) as defective_count')->group("size_name")->select();
				$data['data'][$k]['osList'] = $osList;
				$data['data'][$k]['stockList']=db('sku_stock')->where(['sku' => $v['sku'], 'client_ordernum' => $v['client_ordernum']])->field('size_name,available_count,defective_count')->group("size_name")->select();
                $data['data'][$k]['otherStockList']=$otherStockList;
                $data['data'][$k]['otherStockCount']=array_sum(array_column($otherStockList,'available_count'));
                $data['data'][$k]['otherStockList_json']=json_encode($otherStockList);
                $data['data'][$k]['osJson'] = json_encode($osList);
				$data['data'][$k]['groupKV'] = [0 => '请选择'] + getGroupKV($v['factory_id']);
				$data['data'][$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'jiaohuo_tail_count' => array_sum(array_column($osList, 'jiaohuo_tail_count')), 'delivery_count' => array_sum(array_column($osList, 'delivery_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
				$data['data'][$k]['shipment_time_diff'] = $v['status'] == 2 ? formatSecond($v['shipment_time'] - $v['over_time']) : formatSecond($v['shipment_time'] - time());
				$data['data'][$k]['create_time_diff'] = $v['status'] == 2 ? formatSecond($v['over_time'] - $v['shipment_time']) : formatSecond(time() - $v['shipment_time']);
				$data['data'][$k]['o_type_text'] = arrayGet(config('mimo.order_otype'), $v['o_type'], '');
				$data['data'][$k]['delete_text'] = $v['status'] == 99 ? '已废除' : '';
				$data['data'][$k]['sInfo'] = $skuService->getInfoBySku($v['sku']);
				$data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
				$data['data'][$k]['group_name'] = arrayGet($groupKV, $v['group_id'], '');
				$data['data'][$k]['factory_outgo_name'] = arrayGet($factoryOutgoKV, $v['factory_outgo_id'], '');
				$data['data'][$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
				$data['data'][$k]['caigou_user_name'] = arrayGet($systemUserKV, $v['caigou_user_id'], '');
                $data['data'][$k]['delivery_list'] = explode(',',$v['chird_delivery_status']);
				$data['data'][$k]['is_delivery'] = in_array($v['id'], $orderDeliveryList) ? 1 : 0; // 是否有发货单
                $data['data'][$k]['finishinfo']=db('order_finish')->where([ 'order_id' => $v['id']])->find();
                //断码
                $data['data'][$k]['break_code']='';
                if($v['tail_status'] !=1){
                    $break_info=db('order_break')->field('size_list')->where([['client_ordernum', '=', $v['client_ordernum']],['sku','=', $v['sku']]])->find();
                    $data['data'][$k]['break_code']=isset($break_info['size_list'])?$break_info['size_list']:'';
                }
			}
            if ($export) {
                $this->tailDataExpXls('尾部进度-' .date('YmdHi'), $data['data']);
                exit;
            }
			$data['count'] = db('order o')
                ->join([$usedStockData=> 'delivery'], 'o.id = delivery.order_id '.$sqlwhere,$joinType)
                ->where($where)->count('id');
			$data['code'] = 0;
			$data['msg'] = '';
			return json($data);
		}

		$assign = [
			'factoryKV' => [0 => '请选择'] + $factoryKV,
			'groupKV' => $groupKV,
			'factoryOutgoKV' => $factoryOutgoKV,
            'orderFrom' => [0 => ''] + config('mimo.order_from'),
            'delivery_status' => config('mimo.delivery_status')
		];
		return $this->assign($assign)->fetch();
	}

	/**
	 * 尾部完成
	 */
	public function done() {
		$orderId = $this->request->param('order_id/d');
		$isDone = $this->request->param('is_done/d', 0);
		$numberArr = $this->request->param('number/a', []);
        //委外管理卡点
        $temp = (new \app\common\service\OrderOutgo())->tail_done_check($orderId);
        if ($isDone == 1 && $temp['code'] > 0) {
            return $this->Json(0, $temp['msg']);
        }

		try {
			db()->startTrans();

			$result = false;
			foreach ($numberArr as $k => $v) {
				$data = array();
				$data['jiaohuo_tail_count'] = $v ? $v : 0;
				$data['update_time'] = time();
				$res = db('order_size')->where('mid', $k)->where('order_id', $orderId)->update($data);
			}

			$oData = array();
			$orderService = new OrderService();
			$orderInfo = $orderService->getInfoById($orderId);

			if ($orderInfo['caichuang_over_time'] == 0) {
				$oData['caichuang_status'] = 1;
				$oData['caichuang_over_time'] = time()-2;
			}

			if ($orderInfo['chejian_over_time'] == 0) {
				$oData['chejian_status'] = 1;
				$oData['chejian_over_time'] = time()-1;
			}

			// 订单的车间状态操作
			if ($isDone) {
				$oData['tail_status'] = 1;
				$oData['tail_over_time'] = time();

				$msg = "尾部完成，" ;
			} else {
				$msg = "后整数录入成功，";
			}

			if (env('mes_api_status') == 1) {
				// 同步发货单
				//$output = Console::call('cronSyncDeliveryOrder', ['--print=0', '--client_ordernum='.$orderInfo['client_ordernum'], '--mes='.$orderInfo['is_auto_import'], '--force=1']);
				//$resA = json_decode($output->fetch(), true);
				//$msg .= arrayGet($resA, 'msg', '');
                db('order')->where('id', $orderId)->update(['delivery_sync_status' => 2, 'update_time' => time()]);
                $this->addOrderLog($orderId, $orderInfo['client_ordernum'], '申请同步发货单');
			}

			db('order')->where("id", $orderId)->update($oData);

			$this->addOrderLog($orderId, $orderInfo['client_ordernum'], $msg);

            //尾部完成时 同步 外发厂的信息状态
            $isDone == 1 && (new \app\common\service\OrderOutgo())->tail_done($orderId);
            db()->commit();

			return $this->Json(1, $msg);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}

    /**
     * 设置订单完成入仓加入成品统计
     * @author sparkguo  sparkguo@126.com
     */
    public function setOrderFinish(){
        $orderId = $this->request->param('order_id');
        $peopleStoreCount = $this->request->param('people_in_store_count', '0');
        try {
            db()->startTrans();
            $insData = [
                'order_id' => $orderId,
                'join_finish_state' => 1,
                'people_in_store_count' => $peopleStoreCount,
                'edit_join_admin_id' => ADMIN_ID,
                'join_time'=>time(),
                'create_time'=>time()
            ];
            $finishdata=db('order_finish')->where('order_id', $orderId)->find();
            if(empty($finishdata)){
                $finishid = db('order_finish')->insertGetId($insData);
            }else {
                unset($insData['create_time']);
                $finishid=$finishdata['id'];
                db('order_finish')->where('order_id', $orderId)->update($insData);
            }
            if($peopleStoreCount>0){
                db('order')->where("id", $orderId)->update(['store_count'=>$peopleStoreCount]);
            }
            $this->addOrderLog($orderId, '', '设置入仓数，订单加入成衣统计');
            db()->commit();

            return $this->Json(1);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     *获取mes 尾部库存
     */
    public function getMesTails(){
        set_time_limit(0);
        $mesLib = new Mes();
        $result = $mesLib->getMesSkuStocks(1,50);
        $logtxt= 'totalpage'.$result['totalPageNo'];
        addLog($logtxt, 'getMesTails');
        //print_r($result);die;

        for($x=69; $x<=$result['totalPageNo']; $x++){
            $logtxt=$x."--";
            echo  $logtxt;
            addLog($logtxt, 'getMesTails');
            sleep(2);
            $result = $mesLib->getMesSkuStocks($x,50);
              $tailStocks=$result['info'];
              foreach ($tailStocks as $key=>$item){
                  $item['sizeInfo']=empty($item['sizeInfo']) ? '' : $item['sizeInfo'];
                  $insData=[ "sku"=>$item['skc'],"mes_count"=>$item['totalSurplus'], "mes_detail"=>$item['sizeInfo'],"update_time"=>time(), "create_time"=>time()];
                  $finishdata=db('sku_stock_mes')->where('sku', $item['skc'])->find();
                  if(empty($finishdata)){
                      $finishid = db('sku_stock_mes')->insertGetId($insData);
                  }else {
                      unset($insData['create_time']);
                      db('sku_stock_mes')->where('sku', $item['skc'])->update($insData);
                  }
              }
        }
        echo "全部已完成";
    }

    //获取某页尾货数
    public function getmestail(){
        $page= $this->request->param('page',20);
        $mesLib = new Mes();
        $result = $mesLib->getMesSkuStocks($page,50);
        $logtxt= 'totalpage'.$result['totalPageNo']."-current page:".$page."<BR>";
        echo $logtxt;
        $tailStocks=$result['info'];
        foreach ($tailStocks as $key=>$item){
            print_r($item);
            echo "<br>";
        }
    }

	/**
	 * 库存进出
	 */
	public function stockOutIn() {
		$orderId = $this->request->param('order_id');
		$numberArr = $this->request->param('number/a', []);

		$skuStockMapService = new SkuStockMapService();
		$orderService = new OrderService();
		$orderSizeService = new OrderSizeService();
		$orderInfo = $orderService->getInfoById($orderId, 'sku,client_ordernum');
		try {
			db()->startTrans();

			$result = false;
			foreach ($numberArr as $k => $v) {
				$orderSizeInfo = $orderSizeService->getInfoById($k, 'size_name');
				$ret = $skuStockMapService->checkStock($orderInfo['sku'], trim($orderSizeInfo['size_name']), $v);
				if (!$ret) {
					throw new \Exception("尺码{$orderSizeInfo['size_name']}库存数量不足");
				}
				$data = array();
				$data['tail_stock_in_out'] = $v ? $v : 0;
				$data['update_time'] = time();
				$res = db('order_size')->where('mid', $k)->where('order_id', $orderId)->update($data);
			}

			$this->addOrderLog($orderId, $orderInfo['client_ordernum'], '保存库存进出数据');
			db()->commit();

			return $this->Json(1);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}

	/**
	 * 次品录入
	 */
	public function defective() {
		$orderId = $this->request->param('order_id');
		$numberArr = $this->request->param('number/a', []);

		try {
			db()->startTrans();

			$result = false;
			foreach ($numberArr as $k => $v) {
				$data = array();
				$data['tail_defective'] = $v ? $v : 0;
				$data['update_time'] = time();
				$res = db('order_size')->where('mid', $k)->where('order_id', $orderId)->update($data);
			}

			$this->addOrderLog($orderId, '', '次品录入');
			db()->commit();

			return $this->Json(1);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}

	/**
	 * 申请同步发货单
	 *
	 * @author King
	 * @date 2021年8月3日
	 *
	 */
	public function deliverySync() {
		$orderId = $this->request->param('order_id/d', 0);

		try {
			db()->startTrans();

			if (env('mes_api_status') == 0) {
				throw new \Exception('未对接mes API');
			}

			$orderService = new OrderService();
			$orderInfo = $orderService->getInfoById($orderId, 'id,client_ordernum');
			if (!$orderInfo) throw new \Exception('未找到订单信息');

			db('order')->where('id', $orderId)->update(['delivery_sync_status' => 2, 'update_time' => time()]);
			$this->addOrderLog($orderId, $orderInfo['client_ordernum'], '申请同步发货单');
			db()->commit();

			return $this->Json(1, '', ['order_id' => $orderId]);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}

	/**
	 * 查看发货单
	 *
	 * @author King
	 * @date 2021年8月3日
	 *
	 */
	public function deliveryList() {
		$orderId = $this->request->param('order_id/d', 0);

		$orderService = new OrderService();
		$orderInfo = $orderService->getInfoById($orderId, 'id,client_ordernum,real_shipment_status,status');

		$orderSizeService = new OrderSizeService();
		$sizeList = $orderSizeService->getListByOrderId($orderId, 'size_name,order_count');

		$orderDeliveryService = new OrderDeliveryService();
		$deliveryList = $orderDeliveryService->getListByOrderId($orderId, 'id,sub_client_ordernum,delivery_count,delivery_detail,delivery_status,store_count,store_detail,real_shipment_detail,real_shipment_count');

		$assign = [
			'orderInfo' => $orderInfo,
			'sizeList' => $sizeList,
			'deliveryList' => $deliveryList,
			'deliveryStatusMap' => config('mimo.delivery_status')
		];
		// dump($assign);exit;
		return $this->assign($assign)->fetch();
	}

	/**
	 * 保存实际出货数
	 *
	 * @author King
	 * @date 2021年8月3日
	 *
	 */
	public function deliverySave() {
		$orderId = $this->request->param('order_id/d', 0);
		$realShipmentArr = $this->request->param('real_shipment/a', []);

		try {
			db()->startTrans();

			$orderService = new OrderService();
			$orderInfo = $orderService->getInfoById($orderId, 'id,client_ordernum');
			if (!$orderInfo) throw new \Exception('未找到订单信息');

			$upData = [];
			$ids = array_keys($realShipmentArr);
			$total = 0;
			foreach ($ids as $id) {
				$detail = [];
				$count = 0;
				foreach ($realShipmentArr[$id] as $k => $v) {
					$detail[] = [
						'quantity' => $v,
						'sizeName' => $k,
					];
					$count += $v;
				}
				$total += $count;
				db('order_delivery')->where('id', $id)->update(['real_shipment_detail' => json_encode($detail), 'real_shipment_count' => $count, 'update_time' => time()]);
			}

			// 更新order_size表的出货数
			$orderDeliveryService = new OrderDeliveryService();
			$realShipmentList = $orderDeliveryService->getListByOrderId($orderId, 'real_shipment_detail,delivery_status');
			$realShipmentCountMap = [];

			foreach ($realShipmentList as $v) {
				if($v['real_shipment_detail'] && !in_array($v['delivery_status'], [6, 7])) {
					foreach ($v['real_shipment_detail'] as $sizeName => $quantity) {
						if (isset($realShipmentCountMap[$sizeName])) $realShipmentCountMap[$sizeName] += $quantity;
						else $realShipmentCountMap[$sizeName] = $quantity;
					}
				}
			}
			foreach ($realShipmentCountMap as $sizeName => $count) {
				db('order_size')->where('order_id', $orderId)->where('size_name', $sizeName)->update(['daohuo_count' => $count, 'update_time' => time()]);
			}

			db('order')->where('id', $orderId)->update(['real_shipment_status' => 1, 'real_shipment_count' => $total, 'real_shipment_time' => time(), 'update_time' => time()]);

			$this->addOrderLog($orderId, $orderInfo['client_ordernum'], '实际发货数录入');
			db()->commit();

			return $this->Json(1, '', ['order_id' => $orderId]);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}

	}

    /**
     * 成衣入库操作
     * @author sparkguo
     * 2021-08-27
     */
	public function stockCheckIn(){
        $orderId = $this->request->param('order_id');
        $sizeName=$this->request->param('size_name');
        $dressCode=trim($this->request->param('dress_line_code'),";");
        $stockType=$this->request->param('stocktype');
        $defective_reason=$this->request->param('defective_reason');
        $orderService = new OrderService();
        $orderInfo = $orderService->getInfoById($orderId, 'sku,client_ordernum,factory_id');
        $dressCode=$dressCode.";";
        $dressCodeArr=explode(";",$dressCode);
        unset($dressCodeArr[count($dressCodeArr)-1]);
        foreach ($dressCodeArr as $key=>$dressCodeStr){
            $newDressArr[$dressCodeStr]=$key;
        }
        if(count($newDressArr)>1){
            return $this->Json(0,'存在不同的条码,请确认');die;
        }
        $oldstock=0;
        $oldStockInfo=db('sku_stock')->where(['sku' => $orderInfo['sku'], 'factory_id' => $orderInfo['factory_id'],'size_name'=>$sizeName,'client_ordernum' => $orderInfo['client_ordernum']])->find();
        $has_dress_code=db('sku_stock')->where(['dress_line_code' => $dressCodeArr[0]])->find();
        if($oldStockInfo && $oldStockInfo['dress_line_code']!=$dressCodeArr[0] && !empty($oldStockInfo['dress_line_code'])){
            return $this->Json(0,$sizeName.'已入库，条码为'.$oldStockInfo['dress_line_code'].',请确认当前条码');die;
        }
        if($has_dress_code ){
            if($has_dress_code['size_name']!=$sizeName || $has_dress_code['sku']!=$orderInfo['sku'] || $has_dress_code['client_ordernum']!=$orderInfo['client_ordernum']){
                return $this->Json(0,'条码'.$dressCodeArr[0].'已入库,对应订单号：'.$has_dress_code['client_ordernum'].',尺码：'.$has_dress_code['size_name'].'');die;
            }
        }
        try {
            db()->startTrans();
            $actiontime=time();
            $savedata = ['sku' => $orderInfo['sku'],'available_detail' =>'{"'.$sizeName.'":"'.count($dressCodeArr).'"}',
                'available_count' =>count($dressCodeArr),'size_name'=>$sizeName, 'dress_line_code'=>$dressCodeArr[0],'factory_id'=>$orderInfo['factory_id'],'update_time' => $actiontime,'client_ordernum'=>$orderInfo['client_ordernum']];
            if($stockType=='defective'){
                unset($savedata['available_detail']);unset($savedata['available_count']);
                $savedata['defective_count']=count($dressCodeArr);$savedata['defective_detail']='{"'.$sizeName.'":"'.count($dressCodeArr).'"}';$savedata['defective_reason']=$defective_reason;
            }
            if(!$oldStockInfo){
                $savedata['create_time']=$actiontime;
                db('sku_stock')->insert($savedata);
            }else{
                $oldstock=$oldStockInfo['available_count'];
                $savedata['dress_line_code']=$dressCodeArr[0];
                $savedata['available_detail']='{"'.$sizeName.'":"'.($oldstock+count($dressCodeArr)).'"}';
                $savedata['available_count']=$oldStockInfo['available_count']+count($dressCodeArr);
                if($stockType=='defective'){
                    unset($savedata['available_detail']);unset($savedata['available_count']);
                    $savedata['defective_count']=$oldStockInfo['defective_count']+count($dressCodeArr);$savedata['defective_detail']='{"'.$sizeName.'":"'.($oldStockInfo['defective_count']+count($dressCodeArr)).'"}';
                    $savedata['defective_reason']=$defective_reason;
                }
                db('sku_stock')->where(['id' => $oldStockInfo['id']])->update($savedata);
            }
            $stock_log = ['sku' => $orderInfo['sku'], 'uid' =>ADMIN_ID,'action_type' => 1,'available_detail' =>'{"'.$sizeName.'":"'.count($dressCodeArr).'"}',
                'factory_id' =>$orderInfo['factory_id'],'create_time' => $actiontime,'client_ordernum'=>$orderInfo['client_ordernum']];
            if($stockType=='defective'){
                unset($stock_log['available_detail']);
                $stock_log['defective_count']=count($dressCodeArr);
                $stock_log['defective_detail']='{"'.$sizeName.'":"'.count($dressCodeArr).'"}';$stock_log['defective_reason']=$defective_reason;$stock_log['remark']=$defective_reason;
            }else{
                $stock_log['available_count']=count($dressCodeArr);
            }
            db('sku_stock_log')->insert($stock_log);
            db()->commit();
            $savedata['checkin_count']=count($dressCodeArr);
            return $this->Json(1,'success',$savedata);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 扫码出库操作
     * @author sparkguo
     */
    public function stockCheckOut(){
        $orderId = $this->request->param('order_id');
        $dressCode=trim($this->request->param('out_dress_line_code'),"\n");
        $orderService = new OrderService();
        $orderInfo = $orderService->getInfoById($orderId, 'sku,client_ordernum,factory_id');
        $dressCodeArr=explode("\n",$dressCode);
        $newDressArr=[];
        foreach ($dressCodeArr as $key=>$dressCodeStr){
            if(!isset($newDressArr[$dressCodeStr])){
                $newDressArr[$dressCodeStr]=1;
            }else{
                $newDressArr[$dressCodeStr]++;
            }
        }
        $stockList=db('sku_stock')->where(['sku' => $orderInfo['sku'],'dress_line_code'=>array_keys($newDressArr)])->select();
        if(count($stockList)<count($newDressArr)){
            return $this->Json(0,'出库条码有误，有不存在的出库条码');die;
        }
        $availableCountArr=array_column($stockList,'available_count','dress_line_code');
        foreach ($availableCountArr as $index=>$stockcount){
            if($newDressArr[$index]>$stockcount){
                return $this->Json(0,$index.'出库数量'.$newDressArr[$index].'件超过总库存'.$stockcount.'件，库存不足,请确认');die;
            }
        }
        try {
            db()->startTrans();
            $actiontime=time();
            $act_ret_str='';
            foreach ($stockList as $key=>$stockinfo){
                $savedata = ['sku' => $orderInfo['sku'],'available_detail' =>'{"'.$stockinfo['size_name'].'":"'.($stockinfo['available_count']-$newDressArr[$stockinfo['dress_line_code']]).'"}',
                    'available_count' =>$stockinfo['available_count']-$newDressArr[$stockinfo['dress_line_code']],'update_time' => $actiontime];
                db('sku_stock')->where(['id' => $stockinfo['id']])->update($savedata);
                $stock_log = ['sku' => $orderInfo['sku'], 'uid' =>ADMIN_ID,'available_count'=>$newDressArr[$stockinfo['dress_line_code']],'out_ordernum'=>$orderInfo['client_ordernum'],
                    'action_type' => 2,'available_detail' =>'{"'.$stockinfo['size_name'].'":"'.$newDressArr[$stockinfo['dress_line_code']].'"}',
                    'factory_id' =>$stockinfo['factory_id'],'create_time' => $actiontime,'client_ordernum'=>$stockinfo['client_ordernum'],'remark'=>$orderInfo['client_ordernum']."出货调用"];
                db('sku_stock_log')->insert($stock_log);
                $act_ret_str=$act_ret_str.$stockinfo['size_name'].":".$newDressArr[$stockinfo['dress_line_code']]."件，";
            }
            db()->commit();
            $savedata['act_ret_str']=$act_ret_str;
            return $this->Json(1,'success',$savedata);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

	public function tailDataExpXls($fileName, &$data) {
        $head = ['订单号','SKU','工厂','分组','下单数','裁床数','车间数','后整数','打包数','出货数','未出货','MES入仓数','MES入仓时间','下单时间','尾部完成时间'];
        $params = [];
        $exportdata = [];
        foreach ($data as $k => $v) {
            $total_chuhuo=0;
            foreach($v['osList'] as $i=>$osinfo){
                $total_chuhuo = $total_chuhuo+$osinfo['delivery_count']-$osinfo['daohuo_count'];
            }
            $exportdata[] = [
                $v['client_ordernum'],
                $v['sku'],
                $v['factory_name'],
                $v['group_name'],
                $v['osStat']['order_count'],
                $v['osStat']['shicai_count'],
                $v['osStat']['jiaohuo_count'],
                $v['osStat']['jiaohuo_tail_count'],
                $v['osStat']['delivery_count'],
                $v['osStat']['daohuo_count'],
                $total_chuhuo,//总未出货数
                $v['store_count'],
                $v['store_time']==0 ? '':date('Y-m-d', $v['store_time']),
                $v['create_time']==0 ? '':date('Y-m-d', $v['create_time']),
                $v['tail_over_time']==0 ? '':date('Y-m-d', $v['tail_over_time'])
            ];
        }
        $params['file'] = $fileName;
        $params['sheet'] = [
            [
                'head' => $head, // 表头
                'data' => $exportdata,
            ],
        ];
        unset($data);
        plugins_run('excel/excel/export', $params);
    }
}